package com.example.mallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.example.mallproduct.controller.vo.AttrVO;
import com.example.mallproduct.dao.AttrAttrgroupRelationDao;
import com.example.mallproduct.dao.AttrDao;
import com.example.mallproduct.entity.AttrAttrgroupRelationEntity;
import com.example.mallproduct.entity.AttrEntity;
import com.example.mallproduct.entity.AttrGroupEntity;
import com.example.mallproduct.entity.CategoryEntity;
import com.example.mallproduct.service.AttrAttrgroupRelationService;
import com.example.mallproduct.service.AttrGroupService;
import com.example.mallproduct.service.AttrService;
import com.example.mallproduct.service.CategoryService;
import com.example.mallproduct.service.SkuSaleAttrValueService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<AttrEntity> page;
        QueryWrapper queryWrapper = new QueryWrapper<AttrEntity>();
        if (StringUtils.isNotBlank((String) params.get("key"))) {
            queryWrapper.like("attr_name", params.get("key"));
        }
        if (StringUtils.isNotBlank((String) params.get("catelogId"))) {
            queryWrapper.eq("catelog_id", params.get("catelogId"));
        }
        if (StringUtils.isNotBlank((String) params.get("attrType"))) {
            queryWrapper.eq("attr_type", params.get("attrType"));
        }


        page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );


        page.getRecords().stream().map(attrEntity -> {
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            QueryWrapper queryWrapperRelation = new QueryWrapper<AttrAttrgroupRelationEntity>();
            queryWrapperRelation.eq("attr_id", attrEntity.getAttrId());
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(queryWrapperRelation);
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());

            attrEntity.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            attrEntity.setCatelogName(categoryEntity.getName());
            return attrEntity;

        }).collect(Collectors.toList());


        return new PageUtils(page);
    }

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    /**
     * 保存属性
     *
     * @param attrVO
     * @return
     */
    @Transactional
    @Override
    public boolean saveAttr(AttrVO attrVO) {

        //保存属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        this.save(attrEntity);

        //保存分组与属性关系
        if (null != attrVO.getAttrGroupId()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }

//        if (StringUtils.isNotBlank(attrVO.getValueSelect())) {
//            String[] value = StringUtils.split(attrVO.getValueSelect(), ",");
//            for (String s : value) {
//                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
//                skuSaleAttrValueEntity.setAttrId(attrEntity.getAttrId());
//                skuSaleAttrValueEntity.setAttrName(attrVO.getAttrName());
//                skuSaleAttrValueEntity.setAttrValue(s);
//
//                skuSaleAttrValueService.save(skuSaleAttrValueEntity);
//
//            }
//        }
        return true;
    }

    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 根据分类查询属性
     *
     * @param categoryId
     * @return
     */
    @Override
    public PageUtils infoByCategoryId(Long categoryId) {
        QueryWrapper queryWrapper = new QueryWrapper<AttrEntity>();
        queryWrapper.eq("category_id", categoryId);
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(new HashMap<String, Object>()), queryWrapper);
        CategoryEntity categoryEntity = categoryService.getById(categoryId);
        page.getRecords().stream().map(attrEntity -> {
            attrEntity.getCatelogId();

            QueryWrapper queryWrapperRelation = new QueryWrapper<AttrAttrgroupRelationEntity>();
            queryWrapperRelation.eq("attr_id", attrEntity.getAttrId());
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(queryWrapperRelation);
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());

            attrEntity.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            attrEntity.setCatelogName(categoryEntity.getName());
            return attrEntity;

        }).collect(Collectors.toList());

        return new PageUtils(page);
    }

    @Override
    public AttrEntity info(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        if (null != attrEntity) {

            attrEntity.setCatelogIdList(new ArrayList<>());
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper();
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity =
                    attrAttrgroupRelationService.getOne(queryWrapper.eq("attr_id", attrId));
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            attrEntity.getCatelogIdList().add(attrEntity.getCatelogId());
            attrEntity.setCatelogName(categoryEntity.getName());
            attrEntity.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            attrEntity.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            categoryTree(categoryEntity, attrEntity);
            Collections.reverse(attrEntity.getCatelogIdList());
        }
        return attrEntity;
    }

    public void categoryTree(CategoryEntity categoryEntity, AttrEntity attrEntity) {

        CategoryEntity category = categoryService.getById(categoryEntity.getParentCid());
        if (null != category) {
            attrEntity.getCatelogIdList().add(category.getCatId());
            categoryTree(category, attrEntity);

        }
    }


    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Transactional
    @Override
    public void updateBaseAttr(AttrVO attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        // 1.更新基本数据
        this.updateById(entity);
        // 2.修改分组关联的关系
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(entity.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        // 判断是否存在对应的数据
        Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        if (count > 0) {
            // 说明有记录，直接更新
            attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        } else {
            // 说明没有记录，直接插入
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    /**
     * 查询可以检索的属性
     *
     * @param attrs
     * @return
     */
    @Override
    public List<Long> searchAttr(List<Long> attrs) {

        List<AttrEntity> attrEntityList = this.list(new QueryWrapper<AttrEntity>().in("attr_id", attrs));
        if (!CollectionUtils.isEmpty(attrEntityList)) {
            return attrEntityList.stream().filter(item -> item.getSearchType() == 1).map(item -> item.getAttrId()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}